package com.ningmengs789.live.live.live.common.widget.red;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.ningmengs789.live.R;
import com.ningmengs789.live.http.JsonBuilder;
import com.ningmengs789.live.http.OKHttpUtils;
import com.ningmengs789.live.Interface.RequestCallback;
import com.ningmengs789.live.live.live.common.widget.gift.AbsDialogFragment;
import com.ningmengs789.live.live.live.common.widget.gift.utils.OnItemClickListener;
import com.ningmengs789.live.live.live.play.TCLivePlayerActivity;
import com.ningmengs789.live.live.live.push.TCLiveBasePublisherActivity;
import com.ningmengs789.live.live.response.LivingBonusList;
import com.ningmengs789.live.net.utils.NToast;
import com.ningmengs789.live.net.utils.json.JsonMananger;
import com.ningmengs789.live.ui.widget.shimmer.SwipeRefreshHelper;
import com.ningmengs789.live.ui.widget.shimmer.VerticalSwipeRefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class RobRedPacketDialogFragment extends AbsDialogFragment implements OnItemClickListener {

    private RobRedPacketAdapter mAdapter;
    private List<LivingBonusList.ListBean> mList = new ArrayList<>();

    private VerticalSwipeRefreshLayout mSwipeRefresh;
    private RecyclerView shimmerRecycler;
    private LinearLayoutManager linearLayoutManager;
    private TextView dialog_robrp_tv;

    private String mLiveId;
    private String zbUserId;

    private boolean isLoadingMore = false;
    private int page = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_robrp_list;
    }

    @Override
    protected int getDialogStyle() {
        return R.style.BottomDialog2;
    }

    @Override
    protected boolean canCancel() {
        return true;
    }

    @Override
    protected void setWindowAttributes(Window window) {
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle == null) {
            return;
        }
        mLiveId = bundle.getString("mLiveId");
        zbUserId = bundle.getString("zbUserId");

        mSwipeRefresh = mRootView.findViewById(R.id.swipe_refresh);
        shimmerRecycler = mRootView.findViewById(R.id.shimmer_recycler_view);
        dialog_robrp_tv = mRootView.findViewById(R.id.dialog_robrp_tv);

        linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        shimmerRecycler.setLayoutManager(linearLayoutManager);
        mAdapter = new RobRedPacketAdapter(mContext, this);
        shimmerRecycler.setAdapter(mAdapter);

        shimmerRecycler.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItem;
                int totalItemCount;
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                totalItemCount = linearLayoutManager.getItemCount();

                //表示剩下4个item自动加载，各位自由选择
                // dy>0 表示向下滑动
                if (lastVisibleItem >= totalItemCount - 4 && dy > 0) {
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        page++;
                        loadData();
                    }
                }
            }
        });

        initSwipeRefresh();
        page = 1;
        loadData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void loadData() {
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("fl_uid", zbUserId)
                    .put("live_id", mLiveId)
                    .put("page", page)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/appbonus/living_bonus_list", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                if (page == 1){
                    notData();
                }
            }
            @Override
            public void onSuccess(String result) {
                finishRefresh();
                try{
                    LivingBonusList response = JsonMananger.jsonToBean(result, LivingBonusList.class);
                    isLoadingMore = false;
                    if (page == 1) {
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                    }

                    mList.addAll(response.getList());
                    mAdapter.setCards(mList);

                    mAdapter.notifyDataSetChanged();

                    if (mList.size() == 0){
                        notData();
                    }
                }catch (Exception e){
                    if (page == 1){
                        notData();
                    }
                }
            }
        });
    }

    private void notData(){
        finishRefresh();
        dialog_robrp_tv.setVisibility(View.VISIBLE);
    }

    private void finishRefresh() {
        if (mSwipeRefresh != null) {
            mSwipeRefresh.setRefreshing(false);
        }
    }

    private void initSwipeRefresh() {
        if (mSwipeRefresh != null) {
            SwipeRefreshHelper.init(mSwipeRefresh, new VerticalSwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    page = 1;
                    loadData();
                }
            });
        }
    }

    @Override
    public void onItemClick(Object bean, int position) {
        rob(position);
    }

    private void rob(final int position) {
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("bonus_id", mList.get(position).getId())
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/Appbonus/isrobbed", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                NToast.shortToast(mContext, errInfo);
            }
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject data = new JSONObject(result);
                    int status = data.getInt("status");
                    if (status == 0){//0尚未抢过 1已经抢过
                        grabBonus(position);
                    }else {
                        if (mContext instanceof TCLivePlayerActivity){
                            ((TCLivePlayerActivity)mContext).historyRP(String.valueOf(mList.get(position).getId()),
                                    mList.get(position).getAvatar(), mList.get(position).getUser_nickname());
                        }else if (mContext instanceof TCLiveBasePublisherActivity){
                            ((TCLiveBasePublisherActivity)mContext).historyRP(String.valueOf(mList.get(position).getId()),
                                    mList.get(position).getAvatar(), mList.get(position).getUser_nickname());
                        }
                        dismiss();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void grabBonus(final int position) {
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("bonus_id", mList.get(position).getId())
                    .put("live_id", mLiveId)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/Appbonus/grabBonus", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                NToast.shortToast(mContext, errInfo);
            }
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject data = new JSONObject(result);
                    String status = data.getString("status");
                    String money = data.getString("money");
                    if (mContext instanceof TCLivePlayerActivity){
                        ((TCLivePlayerActivity)mContext).RPResults(String.valueOf(mList.get(position).getId()),
                                mList.get(position).getAvatar(), mList.get(position).getUser_nickname(),
                                status, money);
                    }else if (mContext instanceof TCLiveBasePublisherActivity){
                        ((TCLiveBasePublisherActivity)mContext).RPResults(String.valueOf(mList.get(position).getId()),
                                mList.get(position).getAvatar(), mList.get(position).getUser_nickname(),
                                status, money);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                dismiss();
            }
        });
    }
}
